﻿using PdfChartHelper.Models;
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PdfChartHelper.Writer
{
    /// <summary>
    /// 画折线图思路（和柱状图一样）
    /// 1.坐标轴----->刻度线
    /// 2.确定模型代表点在图上的坐标
    /// 3.连线
    /// </summary>
    public class LineChartWriter
    {
        public static PdfDocument DrawLineChart(int X,int Y,int Width,int Hight, List<LineChart> list)
        {
            PdfDocument doc = new PdfDocument();

            PdfPage page = new PdfPage(doc);

            XGraphics graphics = XGraphics.FromPdfPage(page);


            //Step-One需要根据最大值来确定刻度是多少

            double max = list.Max(item => item.num);

            //如果最大值可以被5整除就把最大值作为最大刻度，假设为1，其他的长度根据和最大值的比例来决定

            int Native = ((int)max);

            int MaxScale = 0;

            if (Native % 5 == 0)
                MaxScale = Native;
            else
            {
                //如果不能被整除，就设置最近的可以被5整除的数作为上限刻度
                MaxScale = (Native / 5 + 1) * 5;
            }

            List<int> scales = new List<int>() { MaxScale / 5, MaxScale / 5 * 2, MaxScale / 5 * 3, MaxScale / 5 * 4, MaxScale }; scales.Sort();

            //先画一个坐标轴
            //graphics.DrawLine(new XPen(XBrushes.Aqua,1), 10, 10, 10, 150); //Y
            //graphics.DrawLine(new XPen(XBrushes.Aqua,1), 5, 140, 180, 140); //X

            graphics.DrawLine(new XPen(XBrushes.Aqua, 1), X, Y, X, Y + Hight + 5); //Y
            graphics.DrawLine(new XPen(XBrushes.Aqua, 1), X - 5, Y + Hight, X + Width, Y + Hight); //X


            //再画刻度线,平行于X轴


            int temp = Hight / 5;
            scales.ForEach(item => {
                graphics.DrawLine(new XPen(XBrushes.Azure, 0.4), X - 2, Hight + Y - temp, X + Width, Hight + Y - temp);
                graphics.DrawString(item.ToString(), new XFont("Arial", 6, XFontStyle.Regular), XBrushes.RoyalBlue, X - 8, Hight + Y - temp - 5);
                temp += Hight / 5;
            });

            //画目标点及连线
            List<XPoint> points_list = new List<XPoint>();
            double tempSpace = (Width / list.Count)/2;
            foreach (LineChart point in list)
            {
                //点的高
                double hight = (point.num / MaxScale) * Hight;

                double width = tempSpace;

                tempSpace += Width / list.Count;

                //确定点
                XPoint xPoint = new XPoint(X+width,Y+Hight - hight);

                //添加下方的说明
                graphics.DrawString(point.desc, new XFont("Arial", 6, XFontStyle.Regular),XBrushes.RoyalBlue ,X+width, Hight + Y + 5);
                points_list.Add(xPoint);
            }
            
            graphics.DrawLines(new XPen(XBrushes.RoyalBlue, 1), points_list.ToArray());

            graphics.Save();

            doc.AddPage(page);

            return doc;

        }
    }
}
